//
//  ChatController.swift
//  聊天界面
//
//  Created by smile on 2019/7/5.
//  Copyright © 2019 ixuea. All rights reserved.
//

import UIKit

//导入TextView显示占位文字框架
import KMPlaceholderTextView

//导入选择图片框架
import PhotoSolution

//导入发布订阅框架
import SwiftEventBus

class ChatController: BaseTitleController {
    
    /// 列表
    @IBOutlet weak var tableView: UITableView!
    
    /// 输入框外部容器
    @IBOutlet weak var vwInputContainer: UIView!
    
    /// 输入框内部容器
    @IBOutlet weak var vwInputBorder: UIView!
    
    /// 输入框
    @IBOutlet weak var tvContent: KMPlaceholderTextView!
    
    /// 用户Id
    var id:String!
    
    /// 会话
    var conversation:JMSGConversation!
    
    /// 列表数据源
    var dataArray:[JMSGMessage] = []

    override func initViews() {
        super.initViews()
        
        //圆角
        ViewUtil.showSmallRadius(vwInputBorder)
        
        //边框
        vwInputBorder.showColorPrimaryBorder()
        
        //让输入框这部分不被软键盘挡住
        vwInputContainer.bottomAnchor.constraint(equalTo: view.keyboardLayoutGuide.topAnchor).isActive=true
        
        //获取用户信息
        UserManager.shared().getUser(StringUtil.unwrap(id)) { (data) in
            self.setTitle(data.nickname)
        }
        
        //注册cell
        //其他人发的文本消息
        tableView.register(UINib(nibName: ChatTextLeftCell.NAME, bundle: nil), forCellReuseIdentifier: ChatTextLeftCell.NAME)
        
        //我发的文本消息
        tableView.register(UINib(nibName: ChatTextRightCell.NAME, bundle: nil), forCellReuseIdentifier: ChatTextRightCell.NAME)
        
        //其他人发的图片消息
        tableView.register(UINib(nibName: ChatImageLeftCell.NAME, bundle: nil), forCellReuseIdentifier: ChatImageLeftCell.NAME)
        
        //我发的图片消息
        tableView.register(UINib(nibName: ChatImageRightCell.NAME, bundle: nil), forCellReuseIdentifier: ChatImageRightCell.NAME)
    }
    
    override func initDatas() {
        super.initDatas()
        
        //创建会话
        //如果本地已经存在
        //不会重复创建
        //而是直接返回已经存在的会话
        JMSGConversation.createSingleConversation(withUsername: id) { (conversation, error) in
            self.conversation=conversation as! JMSGConversation
            
            self.clearUnreadCount()
            
            //发送聊天消息改变了通知
            EventBusUtil.postMessageCountChanged()
            
            self.fetchData()
        }
        
        
    }
    
    /// 清除未读消息
    func clearUnreadCount() {
        self.conversation.clearUnreadCount()
    }
    
    override func initListeners() {
        super.initListeners()
        
        //添加输入框代理
        tvContent.delegate=self
    }
    
    func fetchData() {
        dataArray.removeAll()
        
        loadMore()
    }
    
    func loadMore() {
        //查询历史消息
        conversation.allMessages { (messages, error) in
            if let messages=messages as? [JMSGMessage] {
                self.dataArray=self.dataArray+DataUtil.sortMessage(messages)
                self.tableView.reloadData()
                
                //滚动到底部
                self.scrollBottom()
            }
        }
    }
    
    /// 选择图片点击回调
    ///
    /// - Parameter sender: <#sender description#>
    @IBAction func onSelectImageClick(_ sender: Any) {
        print("ChatController onSelectImageClick")
        
        //初始化图片选择框架
        let photoSolutaion=PhotoSolution()
        
        //设置代理
        photoSolutaion.delegate=self
        
        //返回的图片要压缩
        //不然太大了
        photoSolutaion.customization.returnImageSize = .compressed
        
        //最大选择一张图片
        let pickerController=photoSolutaion.getPhotoPicker(maxPhotos: 1)
        
        //显示控制器
        present(pickerController, animated: true, completion: nil)
    }
    
    /// 发送文本消息
    func sendTextMessage() {
        //获取输入文本
        let content=tvContent.text.trim()!
        
        //判断是否输入文本了
        if content.isEmpty {
            ToastUtil.short("请输入发送的内容！")
            return
        }
        
        sendMessage(JMSGTextContent(text: content))
    }
    
    /// 发送图片消息
    ///
    /// - Parameter data: <#data description#>
    func sendImageMessage(_ data:UIImage) {
        //将图片转为data
        //指令为50%
        //值越小质量越差
        //但是体积越小
        let imageData=data.jpegData(compressionQuality: 0.5)!
        
        sendMessage(JMSGImageContent(imageData: imageData)!)
    }
    
    /// 发送消息
    /// - Parameter data: <#data description#>
    func sendMessage(_ data:JMSGAbstractContent) {
        //设置扩展信息
                
        //目的是实现显示离线通知后，点击跳转到聊天界面
        data.addStringExtra(ACTION_MESSAGE, forKey: ACTION_KEY)
        data.addStringExtra(StringUtil.wrapperUserId(PreferenceUtil.userId()!), forKey: EXTRA_ID)
        
        //发送消息
        conversation.send(conversation.createMessage(with: data)!)
    }
    
    /// 获取cell类型
    ///
    /// - Parameter data: <#data description#>
    /// - Returns: <#return value description#>
    func typeForItemAtData(_ data:JMSGMessage) -> CellType {
        //获取消息的方向
        let isReceived=data.isReceived
        
        //判断消息类型
        if data.contentType == .image {
            //图片消息
            return isReceived ? .imageLeft : .imageRight
        }
        
        //判断是谁发的
        //接收的消息是对方发的；显示到左侧
        //我发送的显示到右侧
        return isReceived ? .textLeft : .textRight
    }
    
    /// cell类型
    ///
    /// - textLeft: 文本消息；左边；其他人发的
    /// - textRight: 文本消息；右边；我发的
    /// - imageLeft: 图片消息；左边；其他人发的
    /// - imageRight: 图片消息；右边；我发的
    enum CellType {
        case textLeft
        case textRight
        case imageLeft
        case imageRight
    }
 
    /// 界面已经显示出来了
    ///
    /// - Parameter animated: <#animated description#>
    override func viewDidAppear(_ animated: Bool) {
        super.viewDidAppear(animated)
        
        //设置聊天框架代理
        JMessage.add(self, with: conversation)
        
        //设置用户Id
        AppDelegate.shared.currentChatUserId=id
    }
    
    /// 界面即将消失
    ///
    /// - Parameter animated: <#animated description#>
    override func viewDidDisappear(_ animated: Bool) {
        super.viewDidDisappear(animated)
        
        //移除聊天代理
        JMessage.remove(self, with: conversation)
        
        //清除用户Id
        AppDelegate.shared.currentChatUserId=nil
    }
    
    /// 显示消息
    ///
    /// - Parameter data: <#data description#>
    func addMesssage(_ data:JMSGMessage) {
        //添加到列表
        dataArray.append(data)

        //刷新列表
//        tableView.reloadData()
        
        //插入一条数据
        let indexPath=IndexPath(item: dataArray.count-1, section: 0)
        tableView.insertRows(at: [indexPath], with: .automatic)
        
        //滚动到底部
        scrollBottom()
    }
    
    /// 清除输入框内容
    func clearTextView() {
        tvContent.text=""
    }
    
    /// 滚动到底部
    func scrollBottom() {
        DispatchQueue.main.async {
            if self.dataArray.count > 0 {
                //有数据才滚动
                let indexPath=IndexPath(item: self.dataArray.count-1, section: 0)
                
                //滚动
                self.tableView.scrollToRow(at: indexPath, at: .bottom, animated: false)
            }
        }
    }
}

// MARK: - 启动方法
extension ChatController{
    
    /// 启动方法
    ///
    /// - Parameters:
    ///   - nav: <#nav description#>
    ///   - id: <#id description#>
    static func start(_ nav:UINavigationController,_ id:String) {
        //创建控制器
        let controller = nav.storyboard!.instantiateViewController(withIdentifier: "Chat") as! ChatController
        
        //传递数据
        controller.id=id
        
        //将控制器放到导航控制器中
        nav.pushViewController(controller, animated: true)
    }
}

// MARK: - 列表数据源和代理
extension ChatController:UITableViewDataSource,UITableViewDelegate{
    
    /// 返回有多少个
    ///
    /// - Parameters:
    ///   - tableView: <#tableView description#>
    ///   - section: <#section description#>
    /// - Returns: <#return value description#>
    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return dataArray.count
    }
    
    /// 返回cell
    ///
    /// - Parameters:
    ///   - tableView: <#tableView description#>
    ///   - indexPath: <#indexPath description#>
    /// - Returns: <#return value description#>
    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        //获取data
        let data=dataArray[indexPath.row]
        
        //获取cell类型
        let type=typeForItemAtData(data)
        
        //获取cell
        var cell:BaseChatCell!
        
        switch type {
        case .textLeft:
            cell=tableView.dequeueReusableCell(withIdentifier: ChatTextLeftCell.NAME, for: indexPath) as! BaseChatCell
        case .imageLeft:
            cell=tableView.dequeueReusableCell(withIdentifier: ChatImageLeftCell.NAME, for: indexPath) as! BaseChatCell
        case .imageRight:
            cell=tableView.dequeueReusableCell(withIdentifier: ChatImageRightCell.NAME, for: indexPath) as! BaseChatCell
        default:
            cell=tableView.dequeueReusableCell(withIdentifier: ChatTextRightCell.NAME, for: indexPath) as! BaseChatCell
        }
        
        //绑定数据
        cell.bindData(data)
        
        //返回cell
        return cell
    }
}

// MARK: - TextView代理
extension ChatController:UITextViewDelegate{
    
    /// 当输入内容
    ///
    /// - Parameters:
    ///   - textView: <#textView description#>
    ///   - range: <#range description#>
    ///   - text: <#text description#>
    /// - Returns: <#return value description#>
    func textView(_ textView: UITextView, shouldChangeTextIn range: NSRange, replacementText text: String) -> Bool {
        
        //判断是否按回车
        if text == "\n"{
            //按回车
            
            self.sendTextMessage()
            
            return false
        }
        
        return true
    }
}

// MARK: - 聊天SDK回调
extension ChatController:JMessageDelegate{
    
    /// 发送消息回调
    ///
    /// - Parameters:
    ///   - message: <#message description#>
    ///   - error: <#error description#>
    func onSendMessageResponse(_ message: JMSGMessage!, error: Error!) {
        if let error=error{
            //发送消息错误
            print("ChatController onSendMessageResponse failed:\(error)")
        }else{
            //发送成功
            print("ChatController onSendMessageResponse success")
            
            //将消息添加到列表
            addMesssage(message)
            
            //清除文本输入框
            clearTextView()
        }
    }
    
    /// 极光聊天在线消息回调
    ///
    /// - Parameters:
    ///   - message: <#message description#>
    ///   - error: <#error description#>
    func onReceive(_ message: JMSGMessage!, error: Error!) {
        print("ChatController onReceive:\(MessageUtil.getUnreadMessageCount())")
    
        //将接收到的消息标记为已读
//        message.setMessageHaveRead { (data, error) in
//
//        }
        
        clearUnreadCount()
        
        if let error=error{
            print("ChatController onReceive setMessageHaveRead failed:\(MessageUtil.getUnreadMessageCount()),\(error)")
        }else{
            //设置成功
            print("ChatController onReceive setMessageHaveRead success:\(MessageUtil.getUnreadMessageCount())")


            //添加到列表
            self.addMesssage(message)

            //发送消息改变了通知
            EventBusUtil.postMessageCountChanged()
        }
    }
}

// MARK: - 图片选择框架代理
extension ChatController:PhotoSolutionDelegate {
    
    /// 选择成功
    ///
    /// - Parameter images: <#images description#>
    func returnImages(_ images: [UIImage]) {
        print("ChatController returnImages:\(images.count)")
        
        //发送图片消息
        let image=images[0]
        
        sendImageMessage(image)
    }
    
    /// 取消选择
    func pickerCancel() {
        
    }
    
    
}
